import {LinesComponent} from '../lines/lines.component';
import {AppProxyComponent} from '../app-proxy/app-proxy.component';
import {AppService} from '../../service/app/app.service';
import {RouterModeComponent} from '../router-mode/router-mode.component';
import {Component, OnInit} from '@angular/core';
import {NzModalRef, NzModalService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {HttpClient, HttpParams} from '@angular/common/http';
import {ElectronService} from 'ngx-electron';
import {interval, Observable, of, timer} from 'rxjs';
import {take} from 'rxjs/operators';
import * as CryptoJS from 'crypto-js';
import Swiper from 'swiper';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  vipInfo = 'vip';
  userName: string;
  signStatus = false;
  enableUseTraffic;
  sublink;
  endTime;
  swiper: Swiper;
  isLoading = false;
  started = false;
  stoped = false;
  userInfo;
  loadingText = '';
  vmesses = [];
  vmessNotFormatter = [];
  current_vmess;
  current_node_info;
  current_node_delay = '';
  changeLineModal: NzModalRef<LinesComponent, any>;
  appProxyModal: NzModalRef<AppProxyComponent, any>;
  routerModal: NzModalRef<RouterModeComponent, any>;
  splashImg;
  connectInfo;
  completed = false;
  isMobile = true;
  userImg = require('../../../assets/my.png');
  vipImg = require('../../../assets/crown.png');
  lineImg = require('../../../assets/line.svg');
  timeImg = require('../../../assets/time.svg');
  flowImg = require('../../../assets/flow.svg');
  appImg = require('../../../assets/app.svg');
  proxyImg = require('../../../assets/proxy.svg');
  isAppProxy = '关闭';
  routerModel = '全局';
  appProxyStatus = false;
  routerModelInfo: string;
  appProxyPackages: any[];
  errorImg;
  slides = [];
  slideLoading = false;
  constructor(private router: Router,
              private http: HttpClient,
              private appService: AppService,
              private modalService: NzModalService,
              private electron: ElectronService) { }

  ngOnInit() {
    this.isMobile = this.electron.isElectronApp;
    this.initImage();
    this.getUserInfo();
    this.getNotice();
    if (!this.electron.isElectronApp) {
      this.appProxyStatus = android.getAppProxyStatus();
      this.appProxyPackages = JSON.parse(android.getApps());
      this.routerModelInfo = android.getRouterModelInfo();
      this.getRouterModalValue(this.routerModelInfo);
      if (this.appProxyStatus) {
        this.isAppProxy = '开启';
      }
    }
  }
  getRouterModalValue(routerValue: string) {
    switch (routerValue) {
      case '0':
        this.routerModel = '全局';
        break;
      case '1':
        this.routerModel = '绕过局域网地址';
        break;
      case '2':
        this.routerModel = '绕过大陆地址';
        break;
      case '3':
        this.routerModel = '绕过局域网及大陆地址';
        break;
    }
  }
  // 初始化按钮图标
  initImage() {
    const status = localStorage.getItem('status');
    if (status === 'off' || status === null) {
      this.splashImg = require('../../../assets/btn_off.png');
      this.errorImg = '../../../assets/btn_off.png';
      this.connectInfo = '未连接';
    } else {
      this.splashImg = require('../../../assets/btn_on.png');
      this.errorImg = '../../../assets/btn_on.png';
      this.connectInfo = '已连接';
    }
  }
  // 获取个人信息
  getUserInfo() {
    this.appService.get(this.appService.urls.userinfo + localStorage.getItem('user_id'),
        {observe: 'response', params: new HttpParams().append('access_token', localStorage.getItem('token'))}).subscribe((resp: any) => {
          if (resp.body.ret === 1) {
            this.completed = true;
            this.userInfo = resp.body;
            switch (this.userInfo.class) {
              case 1:
                this.vipInfo = 'vip';
                break;
              case 2:
                this.vipInfo = 'svip';
                break;
              case 3:
                this.vipInfo = 'ssvip';
                break;
            }
            this.userName = this.userInfo.data.user_name;
            this.signStatus = this.userInfo.data.is_checkin;
            this.endTime = this.userInfo.data.expire_in.split(' ')[0];
            this.enableUseTraffic = this.userInfo.data.trafficInfo.unUsedTraffic;
            this.sublink = this.userInfo.data.sublink;
            this.getDingyue(this.sublink);
          } else {
            this.completed = false;
            this.router.navigate(['login']).catch();
          }
    }, (error) => {
          this.router.navigate(['login']).catch();
    });
  }
  getNotice() {
    this.appService.get(this.appService.urls.ann,
      {observe: 'response', params: new HttpParams().append('access_token', localStorage.getItem('token'))}).subscribe((resp: any) => {
      console.log(resp);
      if (resp.body.ret === 1) {
        for (const item of resp.body.data) {
          this.slides.push(item.content.replace(/<[^>]+>/g, '').replace(/[\r\n]/g, ''));
        }
        this.slideLoading = true;
      } else {
        this.router.navigate(['login']).catch();
      }
    }, (error) => {
      this.router.navigate(['login']).catch();
    });
  }
  // 获取订阅信息
  getDingyue(subLink: string) {
    this.http.get(this.appService.urls.subLink + subLink.split('xyz.vikiqq.xyz')[1]).subscribe((resp: any) => {
    }, (error) => {
      const subLinkBase64 = CryptoJS.enc.Base64.parse(error.error.text.trim()).toString(CryptoJS.enc.Utf8);
      console.log(subLinkBase64);
      const vmess_tmps = subLinkBase64.replace('vmess://', '').split('vmess://');
     for (const item of vmess_tmps) {
       this.vmessNotFormatter.push('vmess://' + item);
       try {
         const vmess = JSON.parse(CryptoJS.enc.Base64.parse(item.trim()).toString(CryptoJS.enc.Utf8));
         console.log(vmess);
         vmess['vmess'] = 'vmess://' + item;
         this.vmesses.push(vmess);
       } catch (e) {
         console.log(e);
       }
     }
     const localVmess = localStorage.getItem('vmess');
      if (localVmess === null || localVmess === 'null') {
            this.current_vmess = this.vmesses[0];
        } else {
        this.current_vmess = JSON.parse(localVmess);
      }
     this.current_node_info = this.current_vmess.ps;
      this.tcpService(this.current_vmess.vmess).subscribe((delay: string) => {
        this.current_node_delay = delay;
      });
      console.log(this.current_node_info);
    });
  }
  // 进入个人信息页面
  enterToUser() {
    this.router.navigate(['user']).catch();
  }
  // 切换线路
  changeLine() {
    LinesComponent.prototype.vmess = this.vmesses;
    this.changeLineModal = this.modalService.create({
      nzTitle: '切换路线',
      nzContent: LinesComponent,
      nzOkDisabled: false,
      nzCancelDisabled: false,
      nzFooter: [
        {
          label: '确定',
          type: 'primary',
          show: true,
          onClick: () => {
            this.changeLineModal.getContentComponent().closeModal();
            this.changeLineModal.getContentComponent().success.subscribe((line: any) => {
              this.changeLineModal.destroy();
              this.isLoading = true;
              this.loadingText = '切换中...';
              this.current_vmess = line;
              localStorage.setItem('vmess', JSON.stringify(this.current_vmess));
              this.current_node_info = this.current_vmess.ps;
              this.stopVPN();
              this.startVPN();
            });
          }
        },
        {
          label: '关闭',
          type: 'default',
          show: true,
          onClick: () => {
            this.changeLineModal.destroy();
          }
        }
      ],
    });
  }

  buyTime() {
    this.router.navigate(['buy']).catch();
  }
  // 开启vpn结果观察者
  startedObserver(): Observable<any> {
    return new Observable((observe) => {
      const i = interval(50).pipe(take(600)).subscribe((val) => {
        if (this.started) {
          i.unsubscribe();
          observe.next(this.started);
          observe.complete();
        }
        if (val === 599) {
          i.unsubscribe();
          observe.error('get user info timeout');
        }
      });
    });
  }
  // 关闭vpn结果观察者
  stopedObserver(): Observable<any> {
    return new Observable((observe) => {
      const i = interval(50).pipe(take(600)).subscribe((val) => {
        if (this.stoped) {
          i.unsubscribe();
          observe.next(this.stoped);
          observe.complete();
        }
        if (val === 599) {
          i.unsubscribe();
          observe.error('get user info timeout');
        }
      });
    });
  }
  // 开启VPN
  startVPN() {
    // pc端
    if (this.electron.isElectronApp) {
        this.electron.ipcRenderer.sendSync('start-vpn', {
            command: 'start',
        platform: this.getPlatformInfo(),
        vmess: JSON.stringify(this.current_vmess)});
    } else {
        android.start(this.current_vmess.vmess);
    }
    timer(2000).subscribe(() => {
      this.started = true;
    });
    this.startedObserver().subscribe(() => {
        this.splashImg = require('../../../assets/btn_on.png');
      this.connectInfo = '已连接';
      this.isLoading = false;
      this.stoped = false;
      localStorage.setItem('status', 'on');
    });
  }
  tcpService(vmess: string) {
    return new Observable((observable: any) => {
      if (this.electron.isElectronApp) {
        const ping = JSON.parse(CryptoJS.enc.Base64.parse(vmess.replace(/[\r\n]/g, '').replace('vmess://', '').trim().trim()).toString(CryptoJS.enc.Utf8));
        observable.next('--' + this.electron.ipcRenderer.sendSync('tcp-service-speed', {platform: this.getPlatformInfo(), pingInfo: JSON.stringify(ping)}));
      } else {
        try {
          observable.next('--' + android.ping(vmess));
        } catch (e) {
          observable.next('');
        }
      }
    });
  }
  // 关闭VPN
  stopVPN() {
    if (this.electron.isElectronApp) {
        this.electron.ipcRenderer.sendSync('stop-vpn', {platform: this.getPlatformInfo(), command: 'stop'});
    } else {
        android.stop();
    }
    timer(2000).subscribe(() => {
      this.stoped = true;
    });
    this.stopedObserver().subscribe(() => {
      this.connectInfo = '未连接';
        this.splashImg = require('../../../assets/btn_off.png');
      this.isLoading = false;
      this.started = false;
      localStorage.setItem('status', 'off');
    });
  }
  // 获取平台信息
  getPlatformInfo() {
    const currentPlatfrom = window.navigator.platform.toLocaleLowerCase();
    let platform;
    if (currentPlatfrom.indexOf('mac') !== -1) {
      platform = 'mac';
    } else if (currentPlatfrom.indexOf('win') !== -1) {
      platform = 'windows';
    } else if (currentPlatfrom.indexOf('linux') !== -1) {
      platform = 'linux';
    }
    return platform;
  }
  changeAppProxy() {
    AppProxyComponent.prototype.apps = this.appProxyPackages;
    AppProxyComponent.prototype.status = this.appProxyStatus;
    this.appProxyModal = this.modalService.create({
      nzTitle: '分应用设置',
      nzContent: AppProxyComponent,
      nzOkDisabled: false,
      nzCancelDisabled: false,
      nzFooter: [
        {
          label: '确定',
          type: 'primary',
          show: true,
          onClick: () => {
            this.appProxyModal.getContentComponent().changeAppProxy();
            this.appProxyModal.getContentComponent().success.subscribe((result: any) => {
              this.appProxyModal.destroy();
              android.setAppProxyStatus(result.proxyStatus);
              android.setAppProxyPackages(result.proxyPackages);
              this.appProxyStatus = result.proxyStatus;
              if (result.proxyStatus) {
                this.isAppProxy = '开启';
              } else {
                this.isAppProxy = '关闭';
              }
            });
          }
        },
        {
          label: '关闭',
          type: 'default',
          show: true,
          onClick: () => {
            this.appProxyModal.destroy();
          }
        }
      ],
    });
  }

  changeProxyModel() {
    // this.router.navigate(['router']).catch();
    RouterModeComponent.prototype.routerValue = this.routerModelInfo;
    this.routerModal = this.modalService.create({
      nzTitle: '路由模式',
      nzContent: RouterModeComponent,
      nzOkDisabled: false,
      nzCancelDisabled: false,
      nzFooter: [
        {
          label: '确定',
          type: 'primary',
          show: true,
          onClick: () => {
            this.routerModal.getContentComponent().closeModel();
            this.routerModal.getContentComponent().success.subscribe((result: string) => {
              this.routerModal.destroy();
              android.setRouterModelInfo(result);
              this.routerModelInfo = result;
              this.getRouterModalValue(this.routerModelInfo);
            });
          }
        },
        {
          label: '关闭',
          type: 'default',
          show: true,
          onClick: () => {
            this.routerModal.destroy();
          }
        }
      ],
    });
  }
  // 连接控制
  connectControl() {
    this.isLoading = true;
    const status = localStorage.getItem('status');
    if (status === 'off' ||  status === null) {
      this.connectInfo = '等待连接';
      this.loadingText = '连接中...';
      this.startVPN();
    } else {
      this.loadingText = '关闭中...';
      this.stopVPN();
    }
  }
}
